package com.jf.controller;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.jf.bean.Kaptcha;
import com.jf.service.KaptchaService;
import com.jf.service.impl.KaptchaServiceImpl;
import com.jf.util.MyUtils;
import com.jf.util.ResultJson;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

@WebServlet("/kaptcha.jpg")
public class KaptchaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String uuid = request.getParameter("uuid");
        if(MyUtils.isStringEmpty(uuid)){
            response.getWriter().println(JSON.toJSON(ResultJson.error("UUID不能为空！")));
        }else{


            Properties prop = new Properties();
            Config config = new Config(prop);

            /*获取验证码服务类*/
            KaptchaService kaptchaService = new KaptchaServiceImpl();

            /*生产类*/
            Producer producer = config.getProducerImpl();
            String text = producer.createText();// 获取验证码文本内容

            /*验证码文本存入数据库*/
            Kaptcha kaptcha = new Kaptcha();
            kaptcha.setUuid(uuid);
            kaptcha.setText(text);
            int result=kaptchaService.save(kaptcha);
            if(result>0){
                response.setDateHeader("Expires", 0L);
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                response.addHeader("Cache-Control", "post-check=0, pre-check=0");
                response.setHeader("Pragma", "no-cache");
                response.setContentType("image/jpeg");
                BufferedImage bi = producer.createImage(text);// 获取验证码图片
                ServletOutputStream out = response.getOutputStream();
                /*禁用缓存，可以解决部分同学电脑因为权限问题导致的500错误*/
                ImageIO.setUseCache(false);
                ImageIO.write(bi, "jpg", out);
            }else{
                response.getWriter().println(JSON.toJSON(ResultJson.error("UUID不能重复！")));
            }


        }




    }
}
